#!/usr/bin/env ts-node

import { StockDataCrawler } from '../services/StockDataCrawler';

async function main() {
  console.log('🚀 开始批量导入完整A股股票数据 (5470+ 只)...');
  
  const crawler = new StockDataCrawler({
    batchSize: 300, // 大批次处理
    delayBetweenBatches: 500 // 较短延迟
  });

  const startTime = Date.now();

  try {
    // 导入所有A股数据
    await crawler.importAllAStocks();
    
    const duration = Math.round((Date.now() - startTime) / 1000);
    console.log(`✅ 股票数据导入完成! 用时: ${duration} 秒`);
    
    // 显示统计信息
    const { PrismaClient } = await import('@prisma/client');
    const prisma = new PrismaClient();
    
    const totalStocks = await prisma.stock.count();
    console.log(`\n📊 导入统计:`);
    console.log(`总股票数: ${totalStocks}`);
    
    // 市场分布统计
    const marketStats = await prisma.stock.groupBy({
      by: ['marketId'],
      _count: { _all: true }
    });
    
    const markets = await prisma.market.findMany();
    const marketMap = new Map(markets.map(m => [m.id, m]));
    
    console.log('\n🏢 市场分布:');
    for (const stat of marketStats) {
      const market = marketMap.get(stat.marketId);
      console.log(`${market?.marketName}: ${stat._count._all} 只`);
    }
    
    // 板块分布统计
    const sectorStats = await prisma.stock.groupBy({
      by: ['sector'],
      _count: { _all: true }
    });
    
    console.log('\n🎯 板块分布:');
    for (const stat of sectorStats.slice(0, 10)) { // 只显示前10个
      const sector = stat.sector || '未分类';
      console.log(`${sector}: ${stat._count._all} 只`);
    }
    
    // 实时数据统计
    const realtimeCount = await prisma.stockRealtime.count();
    console.log(`\n📈 有实时数据的股票: ${realtimeCount} 只`);
    
    await prisma.$disconnect();
  } catch (error) {
    console.error('❌ 导入失败:', error);
    process.exit(1);
  }
  
  console.log('🎉 程序执行完成');
  process.exit(0);
}

// 运行主函数
main().catch(console.error);